import os
import subprocess
import datetime
import time
import subprocess
import psutil
from notebook.auth import passwd
import argparse
import shutil


base = "F:\\workspace\\hj\\python\\users\\"
#base = "C:\\Users\\98657\\Desktop\\722\\users\\"
#base = "C:\\manage\\hj\\users\\"
command_str = "jupyter notebook --config {configfile}"
user_file_path = base+"{user}"
user_config_path = base+"{user}\\config.py"


def get_user_singed_port(user):               #return user's port
     path = user_config_path.format(user=user)
     #print("?")
     lines = open(path, 'r').readlines()
     p=lines[-1].split(" = ")
     #print("?????"+str(p))     
     return p[1]      


def getpid(port):                             #return current pid
    net_con = psutil.net_connections()
    pid = 0
    for e in net_con:
        if e.laddr.port == port:
            pid=e.pid
            return pid
            #break
    return pid
    
def shutdown(user,port):
     pid = getpid(port)  
     while pid != 0:    
       process = psutil.Process(pid)
       process.terminate()
       s = "port:{port} has released".format(port = port)
       print(s)
       time.sleep(0.1)
       pid = getpid(port)
     path =  user_file_path.format(user = user)
     shutil.rmtree(path)
     s = "user:{user} logout".format(user = user)
     print(s)
     return True 

def run(timeout,user,port):
   # establish command
   #print("t3")   
   uConfigStr = user_config_path.format(user = user)
       #print(uConfigStr)
   command = command_str.format(configfile = uConfigStr)
   #print(command)
  
   ping = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
   #time.sleep(0.1) 
   #count = 0 
   #print(">")
   ##t = int(timeout)
   #current = datetime.datetime.now()
   #limit = current + datetime.timedelta(seconds = t)
   #print(t)   
   #while (datetime.datetime.now() < limit):
     #print(">")
     #count_now = t - count
     #print(count_now)
     #time.sleep(0.3)
     #count += 1
   #print("off")
   #c = False
   #port = int(port)   
   #while not c:
     #c = shutdown(user,port)
    



if __name__ == '__main__':
    parser = argparse.ArgumentParser(prog='t3.py')
    parser.add_argument('-timeout',nargs='+',type=str)
    #parser.add_argument('-cmd',nargs='+',type=str)
    parser.add_argument('-user',nargs='+',type=str)
    parser.add_argument('-port',nargs='+',type=str)
    opt = parser.parse_args()
    run(opt.timeout[0],opt.user[0],opt.port[0])